/*
 * Copyright (C) 2010 Zaizi Limited.
 * 
 * This file is part of Zaizi's Alfresco FISE integration
 * 
 * Alfresco FISE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Alfresco FISE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Alfresco FISE. If not, see <http://www.gnu.org/licenses/>.
 */
package org.zaizi.fiseiks.alfresco.webscript;

import java.io.IOException;
import java.util.List;

import org.alfresco.model.ContentModel;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.site.SiteInfo;
import org.alfresco.service.cmr.site.SiteService;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;
import org.zaizi.fiseiks.alfresco.service.BasicContent;
import org.zaizi.fiseiks.alfresco.service.FiseIksSearchService;

/**
 * Semantic content retrieval WebScript
 * 
 * @author efoncubierta
 * @see AbstractWebScript
 */
public class GetRelatedContent extends AbstractWebScript
{
	private static Logger logger = Logger.getLogger(GetRelatedContent.class);
	
	// private static final String DEFAULT_MAX_RESULTS = "20"; 

	@SuppressWarnings("unused")
	private ServiceRegistry services;
	private NodeService nodeService;
	private SiteService siteService;
	private FiseIksSearchService fiseSearchService;
	
	/**
	 * Inject Alfresco's service registry
	 * 
	 * @param services Registry of Alfresco's service registry
	 */
	public void setServices(ServiceRegistry services)
	{
		this.services = services;
		this.nodeService = services.getNodeService();
		this.siteService = services.getSiteService();
	}
	
	/**
	 * Inject Fise's search service
	 * @param fiseSearchService Fise's search service
	 */
	public void setFiseSearchService(FiseIksSearchService fiseSearchService)
	{
		this.fiseSearchService = fiseSearchService;
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.springframework.extensions.webscripts.WebScript#execute(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.WebScriptResponse)
	 */
	public void execute(WebScriptRequest req, WebScriptResponse res)
	{
		// Check for entity parameter
		final String entity = req.getParameter("entity");
		if(entity == null)
		{
			logger.error("Unspecified parameter entity");
			return;
		}
		
		// Check for site parameter and load the site
		final String siteId = req.getParameter("site");
		if(siteId == null)
		{
			logger.error("Unspecified parameter siteId");
			return;
		}
		SiteInfo site = siteService.getSite(siteId);
		if(site == null)
		{
			logger.error("Specified site " + siteId + " not exists");
			return;
		}
		
		// Search and iterate over results nodes 
		List<NodeRef> nodes = fiseSearchService.search(siteId, entity);
		JSONArray contents = new JSONArray();
		for(NodeRef nodeRef : nodes)
		{
			// Check if exists, permissions and is locate under the requested site
			if(nodeService.exists(nodeRef) &&
					nodeService.getPath(nodeRef).toString().contains("/{http://www.alfresco.org/model/site/1.0}sites/" +
							"{http://www.alfresco.org/model/content/1.0}" + site.getShortName()))
			{
				BasicContent content = new BasicContent();
				content.setNodeRef(nodeRef);
				content.setTitle((String)nodeService.getProperty(nodeRef, ContentModel.PROP_TITLE));
				contents.put(content.toJSONObject());
			}
		}

		try
		{
			res.setContentType("application/json");
			res.getWriter().append(contents.toString());
		}
		catch (IOException e)
		{
			// TODO: Handle error
			logger.error(e.getMessage(), e);
		}
	}
}